package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmNewsMappper;
import com.heima.wemedia.service.WeNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class WeNewsAutoScanServiceImpl  implements WeNewsAutoScanService {


    @Autowired
    private WmNewsMappper wmNewsMappper;
/*
*
*
* 自媒体文章审核
* */
    @Override
    public void autoScanWeNews(Integer id) {

        //查询自媒体文章
        WmNews wmNews = wmNewsMappper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("自媒体文章不存在");
        }

        //从内容中提取纯文本内容和图片
        HashMap<Object, Object> textAndImg = handleTwxtAndImg(wmNews);

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            //查询文本内容，阿里云接口
       boolean isTextScan=handleTextScan(textAndImg.get("content"),wmNews);

            //审核图片，阿里云接口

            //审核成功，保存app端的文章内容
            ResponseResult responseResult = saveAppNews(wmNews);

        }
    }


    @Autowired
    private IArticleClient iArticleClient;
    /*
    *
    * 审核成功，保存app端的文章内容
    * */
    private ResponseResult saveAppNews(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);


        ResponseResult responseResult = iArticleClient.saveArticle(articleDto);
        return responseResult;
    }

    /*
    *
    * 审核文本内容，阿里云接口
    * */
    private boolean handleTextScan(Object content, WmNews wmNews) {

        return true;
    }

    /*
    *从自媒体文本提取文本和图片
    *
    * */
    private HashMap<Object, Object> handleTwxtAndImg(WmNews wmNews) {
        //提取文本内容
        StringBuilder stringBuilder = new StringBuilder();
        //提取图片
        ArrayList<String> list = new ArrayList<>();

        if(StringUtils.isNotBlank(wmNews.getContent())){
        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
           if(map.get("type").equals("text")){
             stringBuilder.append(map.get("value"));
           }
           if(map.get("type").equals("image")){
            list.add((String) map.get("value"));
           }

        }
    }
        HashMap<Object, Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",list);
        return resultMap;
    }
}
